package com.song.boot.springstudy.netty.idle.reconnect;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 支持重连的客户端Handler
 */
class ReconnectClientHandler extends ChannelInboundHandlerAdapter {
    private ReconnectClient client;
    
    public ReconnectClientHandler(ReconnectClient client) {
        this.client = client;
    }
    
    @Override
    // 表示断开连接的时候触发
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接断开，尝试重连...");
        // 连接断开时触发重连
        client.doConnect();
        super.channelInactive(ctx);
    }
    
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.WRITER_IDLE) {
                // 发送心跳包
                ctx.writeAndFlush("PING");
                System.out.println("发送心跳PING到服务端");
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof String && "PONG".equals(msg)) {
            System.out.println("收到服务端心跳回复PONG");
        } else {
            super.channelRead(ctx, msg);
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常，关闭连接: " + cause.getMessage());
        ctx.close();
    }
}